package com.fjrz.bbxwj.main.mine

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.entity.User
import com.fjrz.bbxwj.entity.UserInfo
import com.fjrz.bbxwj.listener.TabSelectedListener
import com.fjrz.bbxwj.mode.vm.UserViewModel
import com.module.lemlin.base.loadCircleImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.view.LoginAuthPopup
import kotlinx.android.synthetic.main.fragment_user_info.*
import kotlinx.android.synthetic.main.include_mine_heads.*
import java.lang.StringBuilder

class UserInfoFragment : ViewModeFragment<UserViewModel>() {

    companion object {
        private const val EXTRA_NAME_USER_INFO = "EXTRA_NAME_USER_INFO"
        fun newInstance(user: User): UserInfoFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(EXTRA_NAME_USER_INFO, user)
            }
            return UserInfoFragment().apply { arguments = bundle }
        }

        private val videoTabs: MutableList<String> = mutableListOf("作品", "喜欢")
    }

    private val mUser: User?
        get() = arguments?.getSerializable(EXTRA_NAME_USER_INFO) as? User

    override val layoutResId: Int
        get() = R.layout.fragment_user_info

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override fun initView() {

        BarUtils.addMarginTopEqualStatusBarHeight(mToolbarHome)

        //tab&vp
        tabUserInfoVideo.apply {
            addOnTabSelectedListener(TabSelectedListener(requireContext(),R.color.colorMain))
        }.setupWithViewPager(vpUserInfoBody.apply {
            adapter = object : FragmentStatePagerAdapter(
                childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
            ) {

                override fun getItem(position: Int): Fragment =
                    UserVideoFragment.newInstance(position, userId = mUser?.id ?: 0)

                override fun getCount(): Int = videoTabs.size

                override fun getPageTitle(position: Int): CharSequence? {
                    return videoTabs[position]
                }

                override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {}
            }
        })

        //编辑资料
        tvUserInfoEditing.setOnClickListener {
            EditInfoActivity.open(activity = requireActivity())
        }
        tvUserInfoFollowConfirm.setOnClickListener {
            mUser?.let {
                viewModel.userFollow(it.id)
            }
        }
        tvUserInfoFollowClose.setOnClickListener {
            mUser?.let {
                viewModel.userUnFollow(it.id)
            }
        }
    }

    override fun initData() {
        mUser?.let {
            fillData(it)
        }
    }

    override fun onResume() {
        super.onResume()
        mUser?.let {
            viewModel.userInfo(it.id)
        }
    }

    override fun initViewMode() {
        viewModel.userInfoLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code,response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            val userInfo: UserInfo = response.httpData?.data
                ?: return@Observer
            fillData(userInfo)
        })
    }


    override fun onEventMainThread(any: Any) {
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            mUser?.let {
                viewModel.userInfo(it.id)
            }
        }
    }

    private fun fillData(userInfo: UserInfo) {
        tvUserInfoName.text = userInfo.nickname
        tvUserInfoId.text = StringBuilder()
            .append("ID：").append(userInfo.id)
        tvUserInfoDesc.text = if (userInfo.introduction.isNullOrEmpty())
            "个人简介" else userInfo.introduction
        tvUserInfoGreat.text = userInfo.video_likes.toString()
        tvUserInfoFollows.text = userInfo.follows.toString()
        tvUserInfoFans.text = userInfo.fans.toString()
        ivUserInfoAvatar.loadCircleImage(userInfo.avatar)
        if (mUser == null)
            return
        if (mUser!!.who == User.Who.USER_ME) {
            tvUserInfoEditing.visibility = View.VISIBLE
            tvUserInfoFollowClose.visibility = View.GONE
            tvUserInfoFollowConfirm.visibility = View.GONE
            tvUserInfoFollowEach.visibility = View.GONE
        } else if (userInfo.follow_status == 1) {
            tvUserInfoEditing.visibility = View.GONE
            tvUserInfoFollowClose.visibility = View.VISIBLE
            tvUserInfoFollowConfirm.visibility = View.GONE
            tvUserInfoFollowEach.visibility = View.GONE
        } else if (userInfo.follow_status == 2) {
            tvUserInfoEditing.visibility = View.GONE
            tvUserInfoFollowClose.visibility = View.GONE
            tvUserInfoFollowConfirm.visibility = View.VISIBLE
            tvUserInfoFollowEach.visibility = View.GONE
        } else if (userInfo.follow_status == 3) {
            tvUserInfoEditing.visibility = View.GONE
            tvUserInfoFollowClose.visibility = View.GONE
            tvUserInfoFollowConfirm.visibility = View.GONE
            tvUserInfoFollowEach.visibility = View.VISIBLE
        }
    }

    private fun fillData(user: User) {
        tvUserInfoName.text = user.nickname
        tvUserInfoId.text = StringBuilder()
            .append("ID：").append(id)
        tvUserInfoDesc.text = if (user.introduction.isNullOrEmpty())
            "个人简介" else user.introduction
        ivUserInfoAvatar.loadCircleImage(user.avatar)
        if (user.who == User.Who.USER_ME) {
            tvUserInfoEditing.visibility = View.VISIBLE
            tvUserInfoFollowClose.visibility = View.GONE
            tvUserInfoFollowConfirm.visibility = View.GONE
            tvUserInfoFollowEach.visibility = View.GONE
        } else {
            tvUserInfoEditing.visibility = View.GONE
            tvUserInfoFollowClose.visibility = View.GONE
            tvUserInfoFollowConfirm.visibility = View.GONE
            tvUserInfoFollowEach.visibility = View.GONE
        }
    }

}